/*
1、编写程序实现进程的无名管道通信。
	用系统调用pipe( )建立一管道，二个子进程P1和P2分别向管道各写一句话：
		Child 1 is sending a message!
		Child 2 is sending a message!
	父进程从管道中读出二个来自子进程的信息并显示（要求先接收P1，后P2）。
*/

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

#define PIPE_BUFF_SIZE	64

#define string1 "child 1 is sending message!"
#define string2 "child 2 is sending message!"

pid_t p1, p2;


int main()
{
	char dest[PIPE_BUFF_SIZE];
	int rd_fd, wr_fd;
	int pipefd[2];
	
	if(pipe(pipefd) < 0){
		perror("create pipe failed");
		exit(1);
	}else{
		rd_fd = pipefd[0];
		wr_fd = pipefd[1];

		p1 = fork();
		if(p1 < 0){
			perror("fork1 failed");
			return -1;
		}

		if(p1 > 0){
			printf("this is p1 : %d\n", p1);
			close(rd_fd);
			lockf(wr_fd, 1, 0);
			if(write(wr_fd, string1, sizeof(string1)) < 0){
				perror("p1 write pipe failed");
				return -1;
			}
			sleep(5);
			lockf(wr_fd, 0, 0);
			close(wr_fd);
			exit(0);
		}else{
			p2 = fork();
			if(p2 < 0){
				perror("fork 2 failed");
				return -1;
			}
			if(p2 > 0){
				printf("this is p2 : %d", p2);
				close(rd_fd);
				lockf(wr_fd, 1, 0);
				write(wr_fd, string2, sizeof(string2));
				sleep(5);
				lockf(wr_fd, 0, 0);
				close(wr_fd);
				exit(0);
			}else{
				printf("this is father : %d\n", getpid());
				close(wr_fd);
				wait(NULL);
				read(rd_fd, dest, PIPE_BUFF_SIZE);
				printf("father read : %s\n", dest);

				wait(NULL);
				read(rd_fd, dest, PIPE_BUFF_SIZE);
				printf("father read : %s\n", dest);
				exit(0);
			}
		}
	}
}
